// index.js
var app = getApp();
const utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // navTitleText: '',
    goodsResult: [],
    showmsg: "", //判断是否是自己
    scrollHeight: "",
    scrollTop: 0,
    classList: [],
    CurrentPage: 1,
    loadingMoreHidden: 1,
    CurrentPageOff: 1,
    loadingMoreHiddenOff: 1,
    selectedMenuId: 0,
    cateId: 0, //产品标签
    groupId: 0, //195其他分类,375 代金券商品, 376 套餐商品
    Word: '',
    price: '',
    showmenu: false,
    x: 300,
    y: 360,
    x2: 0,
    lastPrice: 0,
    canIUseGetUserProfile: false,
    uid: 0, //供货商ID
    supplyProducts: [],  
    priceDialog:{isShow: false, Pid: 0, CostPrice: 0, SupplyPrice:0}  //修改价格弹框
  },


  // 选择菜单分类
  selectMenu: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.indexid;
    let cid = e.currentTarget.dataset.cid;
    let gid = e.currentTarget.dataset.gid;
    that.setData({
      CurrentPage: 1,
      cateId: cid,
      groupId: gid,
      selectedMenuId: index,
      goodsResultOff: [],
      goodsResult: []
    })   
    that.searchGoods();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(options.uid){
      that.setData({
        uid: options.uid
      })
    }
  },

  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      that.getGoodsClassList();
      that.getSupplyProduct(1);
    } else {
      setTimeout(() => {
        that.onShow()
      }, 1000);
    }
  },

  // 上架商品 
  searchGoods: function () {
    var that = this;
    wx.showLoading({title: '加载中',mask: true})
    let state = 0;
    let groupId = that.data.groupId; 
    wx.request({
      url: app.globalData.host + '/api/product/list',
      data: {
        storeId: app.globalData.storeId,
        groupId: groupId,   //195单品375优惠券376套餐
        cateId: that.data.cateId, //产品标签
        addUid: that.data.uid,
        page: that.data.CurrentPage,
        word: that.data.Word,
        isExtend: 0,
        state: state
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var rawData = res.data.Data;
          var products = rawData.ProductList;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.goodsResult;
            products = preGoods.concat(products);
          }
          for (let i = 0; i < products.length; i++) {
            products[i].currentBuynum = 0;
          }
          that.getCart(products);
          that.setData({
            loadingMoreHidden: rawData.PageModel.TotalPages,
          });
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  getCart: function (products) {
    let that = this;
    let goodsResult = products;
    if (goodsResult.length == 0) {
      return;
    }
    for (let j = 0; j < goodsResult.length; j++) {
      if (goodsResult[j].ShowImg.indexOf('ps') != -1) {
        goodsResult[j].ShowImg = utils.formatAvaterByProHead(goodsResult[j].ShowImg);
      } else {
        goodsResult[j].ShowImg = utils.formatAvater(goodsResult[j].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
      }
      if (goodsResult[j].SendEndTime.indexOf('1970') != -1) {
        goodsResult[j].ExpireTime = '';
      } else {
        goodsResult[j].ExpireTime = goodsResult[j].SendEndTime.substr(0, 10);
        goodsResult[j].ExpireTime = goodsResult[j].ExpireTime.replace(/\//g, "-");
      }
      //是否为带货商品: 0 否, 1 是
      let supply = that.findSupply(goodsResult[j].Pid);
      goodsResult[j].SupplyState = supply !='' ? 1 : 0;
      goodsResult[j].SupplyPrice = supply !='' ? supply.ShopPrice : 0;  //商品销售价格
      goodsResult[j].Price = supply !='' ? supply.ShopPrice : goodsResult[j].ShopPrice;
    }
    that.setData({
      goodsResult: goodsResult
    })
  },
  //是否为带货商品
  findSupply: function(pid){
    let list = this.data.supplyProducts;
    for(let i = 0;i < list.length; i++){
      if(list[i].Pid == pid){
        return list[i];
      }
    }
    return '';
  },

  //获取商品分类列表
  getGoodsClassList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetStoreClassList?storeId=' + app.globalData.storeId + "&uid=" + that.data.uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            var list = res.data.Data;
            var newList = [];
            var other = [];
            for (let i = 0; i < list.length; i++) {
              if(list[i].StoreCid == 0) 
                continue;
              if (list[i].StoreCid == 48917) {
                other = list[i];
              } else {
                newList.push(list[i])
              }
            }
            newList = newList.concat(other);
            that.setData({
              classList: newList
            })
          }
        } else {
          utils.showModal(res.data.Message);         
        }
      },
    })
  },

  loadMore: function (e) {
    let that = this;
    let currPage = that.data.CurrentPage;
    if (that.data.loadingMoreHidden > 1 && currPage < that.data.loadingMoreHidden) {
      that.setData({
        CurrentPage: currPage + 1
      })
      that.searchGoods();
    }
  },
  //已添加的代卖商品
  getSupplyProduct: function(tag = 0){
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Supply/GetAllProduct?saleUid=' + app.globalData.userInfo.Uid +'&uid=' + that.data.uid,
      success: function (res) {
        if (res.data.Code == 0) {    
          if(tag == 1){
            that.searchGoods();  
          }          
          that.setData({
            supplyProducts: res.data.Data
          })     
        } 
      },
    })
  },
  //添加代卖商品
  addProduct: function(e){
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    wx.request({
      url: app.globalData.host + '/api/Supply/AddProduct?saleUid=' + app.globalData.userInfo.Uid + '&pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {        
          utils.showToast('供货商品加入成功');
          setTimeout(() => {
            that.getSupplyProduct(1);  
          }, 500);  
        } 
      },
    })
  },
  //删除代卖商品
  delProduct: function(e){
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    wx.request({
      url: app.globalData.host + '/api/Supply/DeleteProduct?saleUid=' + app.globalData.userInfo.Uid + '&pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {           
          utils.showToast('供货商品删除成功');
          setTimeout(() => {
            that.getSupplyProduct(1);  
          }, 500);
        } 
      },
    })
  },
  //保存代卖商品
  saveProduct: function(e){
    let that = this;
    let p = that.data.priceDialog;
    if(p.SupplyPrice == '' || isNaN(p.SupplyPrice)){
      utils.showToast('请填写正确的销售价格'); return;
    }
    if(p.SupplyPrice  < p.CostPrice){
      utils.showToast('销售价不能低于成本价'); return;
    }
    wx.request({
      url: app.globalData.host + '/api/Supply/UpdateProduct?saleUid=' + app.globalData.userInfo.Uid + '&pid=' + p.Pid + '&shopPrice=' + p.SupplyPrice,
      success: function (res) {
        if (res.data.Code == 0) {           
          that.closeDialog();
          that.getSupplyProduct(1);
          utils.showToast('修改成功');
        }
      },
    })
  },
  
  //修改价格弹框
  editorProduct: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let goodsResult = this.data.goodsResult;    
    let supplyProducts = that.data.supplyProducts;  
    let priceDialog = {isShow: false,Pid: 0, CostPrice: 0, SupplyPrice:0}  
    for(let i = 0;i < goodsResult.length;i++){
      if(goodsResult[i].Pid == pid){
        if(goodsResult[i].SupplyState == 0){
          utils.showToast('添加商品后才能修改价格'); return;
        }
        priceDialog.CostPrice =  goodsResult[i].CostPrice;
        priceDialog.SupplyPrice = goodsResult[i].SupplyPrice;
        priceDialog.isShow = true;
        priceDialog.Pid = pid;
        break;
      }   
    }   
    
    for(let i = 0;i < supplyProducts.length; i++){
      if(supplyProducts[i].Pid == pid){
        priceDialog.CostPrice =  supplyProducts[i].CostPrice;
        priceDialog.SupplyPrice = supplyProducts[i].ShopPrice;
        break;
      }
    }
    
    this.setData({
      priceDialog: priceDialog
    })
  },
  closeDialog: function(){
    let priceDialog={isShow: false, Pid:0, CostPrice: 0, SupplyPrice:0}
    this.setData({
      priceDialog: priceDialog
    })
  },
  toDetails: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let cateid = e.currentTarget.dataset.cateid;
    let url = '/pages/productDetails/index?pid=' + pid + '&seltoid=' + this.data.uid + '&saleUid=' + app.globalData.userInfo.Uid;
    if(cateid==375 || cateid==376){
      url = '/pages/joinDetail/index?pid=' + pid + '&seltoid=' + app.globalData.userInfo.Uid+ '&saleUid=' + app.globalData.userInfo.Uid;
    }
    if(cateid==377 || cateid==378){
      url = '/pages/joinDetail/index?pid=' + pid + '&seltoid=' + this.data.uid + '&saleUid=' + app.globalData.userInfo.Uid+ '&jump=11';
    }
    wx.navigateTo({url: url});
  },
  /** 点击完成按钮是触发 */
  handleConfirm: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 搜索框失去焦点是触发 */
  handleBlur: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 取消搜索 */
  handleCancel: function (e) {
    this.setData({
      Word: ''
    })
  },
  handleInput: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  handleSearchWord: function (e) {
    this.setData({
      CurrentPage: 1,
      loadingMoreHidden: 1,
      selCatId: 0,
      selCatName: '',
      selBrandId: 0,
      selBrandName: '',
      selPriceId: 0,
      selPriceName: '',
      isCategoryTap: false,
      isBrandTap: false,
      isPriceTap: false,
      showSearch: false,
      searchCategory: [], //当前搜索类型
      goodsResult: [],
      goodsResultOff: [],
      CurrentPageOff: 1,
      loadingMoreHiddenOff: 1
    })
    this.searchGoods();
  },

  //获取输入框的值
  getValueInput: function (e) {
    let labelName = e.detail.value;
    this.setData({
      labelName: labelName
    })
  },
  //绑定销售价格
  bindPrice: function (e) {
    let priceDialog= this.data.priceDialog;
    priceDialog.SupplyPrice = e.detail.value;
    this.setData({
      priceDialog: priceDialog
    })
  }
})